import { useState, useEffect } from 'react';
import './index.css';
import axios from "axios";

//观察者模式
export class Observable {
    constructor(value) {
        this.value = value;
        this.observers = [];
    }

    subscribe(observer) {
        this.observers.push(observer);
    }

    notify() {
        this.observers.forEach((observer) => observer(this.value));
    }

    setValue(newValue) {
        if (this.value !== newValue) {
            this.value = newValue;
            this.notify();
        }
    }

    getValue() {
        return this.value;
    }
}

const currentWordIndexObservable = new Observable(0);

const Word = () => {
    const [words, setWords] = useState([]);
    const [difficultyLevel, setDifficultyLevel] = useState('四级词汇');
    const [wordBooks, setWordBooks] = useState([]);
    const [currentWordIndex, setCurrentWordIndex] = useState(0);
    const [reviewStatus, setReviewStatus] = useState({});
    const [activeTab, setActiveTab] = useState('learn');
    const [reviewWords, setReviewWords] = useState([]);
    const [currentReviewIndex, setCurrentReviewIndex] = useState(0);
    const [errorWords, setErrorWords] = useState([]);
    const [showErrorWords, setShowErrorWords] = useState(false);
    const [showChineseMeaning, setShowChineseMeaning] = useState(false);
    const [userId, setUserId] = useState(null);


    useEffect(() => {
        // 订阅 currentWordIndex 的变化
        const observer = (newIndex) => {
            console.log('currentWordIndex updated:', newIndex);
            setCurrentWordIndex(newIndex);
        };

        currentWordIndexObservable.subscribe(observer);

        // 清理订阅
        return () => {
            currentWordIndexObservable.observers = currentWordIndexObservable.observers.filter(
                (o) => o !== observer
            );
        };
    }, []);

    // 组件加载时请求词书列表
    useEffect(() => {
        fetchWordBooks();
        loadUserInfo(); // 加载用户信息
    }, []);

    // 加载用户信息
    useEffect(() => {
        loadUserInfo(); // 加载用户信息并获取进度
        fetchWordBooks();  // 获取词书列表
    }, []);

// 加载用户信息
    const loadUserInfo = async () => {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        const userId = userInfo ? userInfo.userId : null;
        const token = userInfo ? userInfo.token : null;

        if (userId && token) {
            // 使用存储在 localStorage 中的学习进度（如果存在）
            const selectedWordBook = difficultyLevel;  // 使用当前选择的词书名称

            // 加载进度数据，如果存在
            const storedProgress = localStorage.getItem(`progress-${userId}-${selectedWordBook}`);
            if (storedProgress) {
                const parsedProgress = JSON.parse(storedProgress);
                setReviewStatus(parsedProgress.reviewStatus || {});
                setCurrentWordIndex(parsedProgress.currentWordIndex || 0);
                setErrorWords(parsedProgress.errorWords || []);
            } else {
                // 如果没有存储的进度，则从后端加载
                const progressResponse = await fetch(`http://localhost:8080/api/word/user/progress?userId=${userId}&wordBook=${selectedWordBook}`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (progressResponse.ok) {
                    const progressData = await progressResponse.json();
                    setReviewStatus(progressData.progress || {});
                    setErrorWords(progressData.errorWords || []);
                } else {
                    console.error('Failed to fetch progress data:', progressResponse.status);
                }
            }

            setUserId(userId);  // Set userId in state
        }
    };



    // 加载词书列表
    const fetchWordBooks = async () => {
        try {
            const response = await fetch('http://localhost:8080/api/words/wordbooks');
            const data = await response.json();
            setWordBooks(data); // 设置词书列表
        } catch (error) {
            console.error('Error fetching wordbooks:', error);
        }
    };

    // 根据选择的词书加载单词
    useEffect(() => {
        loadWords();
        loadErrorWords();
    }, [difficultyLevel]);

    // 加载单词
    const loadWords = () => {
        const storedWords = localStorage.getItem(`words-${difficultyLevel}`);
        const storedReviewStatus = localStorage.getItem(`reviewStatus-${difficultyLevel}`);
        const storedCurrentWordIndex = localStorage.getItem(`currentWordIndex-${difficultyLevel}`);

        if (storedWords && storedReviewStatus) {
            const parsedWords = JSON.parse(storedWords);  // 直接解析存储的单词
            const parsedReviewStatus = JSON.parse(storedReviewStatus);  // 直接解析复习状态
            setWords(parsedWords);
            setReviewStatus(parsedReviewStatus);
            setCurrentWordIndex(storedCurrentWordIndex ? parseInt(storedCurrentWordIndex) : 0);
        } else {
            fetchWords();
        }
    };

    // 获取单词
    const fetchWords = async () => {
        try {
            const response = await fetch(
                `http://localhost:8080/api/words?difficulty=${difficultyLevel}`
            );
            const data = await response.json();

            const initialReviewStatus = data.reduce((acc, word) => {
                acc[word.word] = { timesReviewed: 0, lastReviewed: Date.now(), interval: 10 };
                return acc;
            }, {});

            setWords(data);
            setReviewStatus(initialReviewStatus);

            // 直接存储数据
            localStorage.setItem(`words-${difficultyLevel}`, JSON.stringify(data));
            localStorage.setItem(`reviewStatus-${difficultyLevel}`, JSON.stringify(initialReviewStatus));
        } catch (error) {
            console.error('Error fetching words:', error);
        }
    };

    // 加载错词列表
    const loadErrorWords = () => {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        const userId = userInfo ? userInfo.userId : null;

        if (userId) {
            const storedErrorWords = localStorage.getItem(`errorWords-${userId}`);
            if (storedErrorWords) {
                setErrorWords(JSON.parse(storedErrorWords));  // 直接解析 JSON 数据
            }
        }

    };

    // 更新学习进度到后端
    const updateUserProgress = async () => {
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        const userId = userInfo ? userInfo.userId : null;

        if (!userId || currentWordIndex === null || !words || words.length === 0) {
            console.error('User ID or current word is missing');
            return;
        }

        const currentWord = words[currentWordIndex]?.word;

        if (!currentWord) {
            console.error('Current word is missing');
            return;
        }

        const wordBook = difficultyLevel;

        const totalWords = words.length;
        const progress = calculateProgress(currentWordIndex, totalWords);

        // 从 reviewStatus 获取当前单词的复习信息
        const currentReviewStatus = reviewStatus[currentWord] || {
            timesReviewed: 0,
            lastReviewed: Date.now(),
            interval: 10,
        };

        try {
            const response = await axios.post('/api/word/user/progress', {
                userId: userId,
                progress: progress,
                wordBook: wordBook,
                word: currentWord,
                timesReviewed: currentReviewStatus.timesReviewed, // 将复习次数传递给后端
                lastReviewed: currentReviewStatus.lastReviewed,   // 最后复习时间
                interval: currentReviewStatus.interval,           // 复习间隔
            }, {
                headers: {
                    Authorization: `Bearer ${userInfo.token}`,
                },
            });

            console.log('User progress updated', response.data);
        } catch (error) {
            console.error('Error updating user progress', error.response?.data || error.message || error);
        }
    };


// 计算学习进度
    const calculateProgress = (currentIndex, totalWords) => {
        return (currentIndex + 1) / totalWords;  // 计算进度: 当前索引 + 1 / 总单词数
    };
// 保存学习进度到 localStorage
    // 保存学习进度到 localStorage
    const saveProgressToLocalStorage = () => {
        const progressData = {
            reviewStatus,
            currentWordIndex,
            errorWords,
        };
        // 直接将数据转换为 JSON 字符串
        localStorage.setItem(`progress-${userId}-${difficultyLevel}`, JSON.stringify(progressData));  // 使用 userId 和 difficultyLevel 作为 key
    };



// 在页面关闭时保存用户进度
    useEffect(() => {
        const handleBeforeUnload = () => {
            updateUserProgress(); // 仅保存进度到后端
            saveProgressToLocalStorage();
        };

        window.addEventListener('beforeunload', handleBeforeUnload);

        return () => {
            window.removeEventListener('beforeunload', handleBeforeUnload);
        };
    }, [reviewStatus, currentWordIndex, errorWords, words]);


    const handleSaveProgress = async () => {
        try {
            await updateUserProgress();  // 调用保存进度的函数
        } catch (error) {
            console.error('保存进度时出错:', error);
            alert('保存进度失败，请稍后再试。');
        }
    };


    // 将单词添加到错词列表
    const handleAddToErrorWords = async () => {
        const currentWord = words[currentWordIndex];
        if (!errorWords.some((word) => word.word === currentWord.word)) {
            const updatedErrorWords = [...errorWords, currentWord];
            setErrorWords(updatedErrorWords);

            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            const userId = userInfo ? userInfo.userId : null;

            if (userId) {
                localStorage.setItem(`errorWords-${userId}`, JSON.stringify(updatedErrorWords));  // 根据 userId 存储错词列表
            }

            // 调用后端API添加错误单词
            await addErrorWordToDatabase(currentWord);
        }
    };

    // 后端API添加错词
    const addErrorWordToDatabase = async (word) => {
        try {
            const userInfoString = localStorage.getItem('userinfo');
            console.log("Retrieved from localStorage:", userInfoString);  // 查看原始字符串数据

            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            const userId = userInfo ? userInfo.userId : null;

            if (!userId) {
                console.error("User ID not found in localStorage.");
            } else {
                console.log("User ID:", userId);
            }

            // 将 userId 添加到 word 对象中
            const wordWithUserId = {
                ...word,
                userId: userId
            };

            console.log("Adding error word with userId:", wordWithUserId);

            const response = await fetch('http://localhost:8080/api/word/user/errorWords', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(wordWithUserId),
            });

            if (!response.ok) {
                throw new Error('Failed to add error word');
            }
        } catch (error) {
            console.error('Error adding error word:', error);
        }
    };



    // 从错词列表中删除单词
    const handleRemoveFromErrorWords = async (wordToRemove) => {
        const updatedErrorWords = errorWords.filter(word => word.word !== wordToRemove.word);
        setErrorWords(updatedErrorWords);

        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        const userId = userInfo ? userInfo.userId : null;

        if (userId) {
            localStorage.setItem(`errorWords-${userId}`, JSON.stringify(updatedErrorWords));  // 根据 userId 存储更新后的错词列表
        }

        // 调用后端API删除错误单词
        await removeErrorWordFromDatabase(wordToRemove);
    };


    // 后端API删除错词
    const removeErrorWordFromDatabase = async (word) => {
        try {
            const userInfo = JSON.parse(localStorage.getItem('userInfo')); // 获取存储在 localStorage 中的 userInfo
            const userId = userInfo?.userId;
            const token = userInfo?.token;  // 获取 Token

            if (!userId || !token) {
                throw new Error("User ID or Token not found in localStorage");
            }

            // 确保 word 是一个字符串
            const wordString = typeof word === 'object' ? word.word : word;  // 假设 word 对象中有 `word` 属性

            // 打印调试信息
            console.log(`Request URL: http://localhost:8080/api/word/user/errorWords?userId=${userId}&word=${encodeURIComponent(wordString)}`);
            console.log('Headers:', {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`,
            });

            const response = await fetch(`http://localhost:8080/api/word/user/errorWords?userId=${userId}&word=${encodeURIComponent(wordString)}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`,  // 确保 token 正确传递
                },
            });

            if (!response.ok) {
                throw new Error('Failed to remove error word');
            }
        } catch (error) {
            console.error('Error removing error word:', error);
        }
    };



    const handleRememberWord = () => {
        const currentWord = words[currentWordIndex];
        const currentStatus = reviewStatus[currentWord.word];

        if (!currentStatus) return;

        let newInterval;

        // 基于艾宾浩斯遗忘曲线模型设定复习间隔
        if (currentStatus.timesReviewed === 1) {
            newInterval = 10 * 60 * 1000; // 第一次复习：10分钟
        } else if (currentStatus.timesReviewed === 2) {
            newInterval = 60 * 60 * 1000; // 第二次复习：1小时
        } else if (currentStatus.timesReviewed === 3) {
            newInterval = 24 * 60 * 60 * 1000; // 第三次复习：1天
        } else if (currentStatus.timesReviewed === 4) {
            newInterval = 3 * 24 * 60 * 60 * 1000; // 第四次复习：3天
        } else if (currentStatus.timesReviewed === 5) {
            newInterval = 7 * 24 * 60 * 60 * 1000; // 第五次复习：1周
        } else if (currentStatus.timesReviewed === 6) {
            newInterval = 14 * 24 * 60 * 60 * 1000; // 第六次复习：2周
        } else if (currentStatus.timesReviewed === 7) {
            newInterval = 30 * 24 * 60 * 60 * 1000; // 第七次复习：1个月
        } else if (currentStatus.timesReviewed === 8) {
            newInterval = 60 * 24 * 60 * 60 * 1000; // 第八次复习：2个月
        } else {
            // 之后复习间隔逐渐增加，每次翻倍，最多不超过1年
            newInterval = Math.min(currentStatus.interval * 2, 365 * 24 * 60 * 60 * 1000);
        }

        const updatedStatus = {
            ...currentStatus,
            timesReviewed: currentStatus.timesReviewed + 1,
            lastReviewed: Date.now(),
            interval: newInterval,
        };

        const updatedReviewStatus = {
            ...reviewStatus,
            [currentWord.word]: updatedStatus,
        };

        setReviewStatus(updatedReviewStatus);

        // 保存更新后的状态（加密）
        localStorage.setItem(`reviewStatus-${difficultyLevel}`, JSON.stringify(updatedReviewStatus));

        startNewRound();
    };

    const startNewRound = () => {
        setCurrentWordIndex((currentWordIndex + 1) % words.length);
        localStorage.setItem(`currentWordIndex-${difficultyLevel}`, currentWordIndex + 1);
        const nextIndex = currentWordIndex + 1;
        currentWordIndexObservable.setValue(nextIndex);
    };

    // 获取复习单词
    const getWordsForReview = () => {
        const now = Date.now();
        const wordsForReview = words.filter((word) => {
            const status = reviewStatus[word.word];
            if (!status) return false;
            const nextReviewTime = status.lastReviewed + status.interval * 1000;
            return nextReviewTime <= now;
        });
        setReviewWords(wordsForReview);
        setCurrentReviewIndex(0);
    };

    // 记住复习单词
    const handleReviewRememberWord = () => {
        if (currentReviewIndex >= reviewWords.length) return;

        const word = reviewWords[currentReviewIndex];
        const currentStatus = reviewStatus[word.word];
        if (currentStatus) {
            const updatedStatus = {
                ...currentStatus,
                timesReviewed: currentStatus.timesReviewed + 1,
                lastReviewed: Date.now(),
                interval: Math.min(currentStatus.interval * 2, 300),
            };
            const updatedReviewStatus = {
                ...reviewStatus,
                [word.word]: updatedStatus,
            };

            setReviewStatus(updatedReviewStatus);

            localStorage.setItem(`reviewStatus-${difficultyLevel}`, JSON.stringify(updatedReviewStatus));

        }

        if (currentReviewIndex + 1 < reviewWords.length) {
            setCurrentReviewIndex(currentReviewIndex + 1);
        } else {
            setReviewWords([]);
            setCurrentReviewIndex(0);

            setTimeout(() => {
                getWordsForReview();
            }, 2000); // 延迟加载复习单词
        }
    };

    // 切换词书
    const handleDifficultyChange = (event) => {
        setDifficultyLevel(event.target.value);
        localStorage.setItem(`currentWordIndex-${difficultyLevel}`, currentWordIndex);
    };

    // 点击单词显示中文意思
    const handleWordClick = () => {
        setShowChineseMeaning(!showChineseMeaning);
    };

    return (
        <div className="word_container">
            <div className="tab-nav">
                <button
                    onClick={() => setActiveTab('learn')}
                    className={activeTab === 'learn' ? 'active' : ''}>
                    Learn
                </button>
                <button
                    onClick={() => {
                        setActiveTab('review');
                        getWordsForReview();
                    }}
                    className={activeTab === 'review' ? 'active' : ''}>
                    Review
                </button>
            </div>

            <button
                className="error-words-button"
                onClick={() => setShowErrorWords(!showErrorWords)}>
                📕ErrorWord
            </button>
            <button
                className="save-progress-button"
                onClick={handleSaveProgress}>
                📄
                <span>保存当前进度</span>
            </button>
            {showErrorWords && (
                <div className="error-words-list">
                    <h3>错词列表</h3>
                    <div className="error-words-scrollable">
                        {errorWords.map((word, index) => (
                            <div key={index} className="error-word">
                                {word.word} - {word.chineseMeaning}
                                <button
                                    className="remove-error-word-button"
                                    onClick={() => handleRemoveFromErrorWords(word)}>
                                    Revome🗑️
                                </button>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            <div className="difficulty-selector">
                <label htmlFor="difficulty">选择词书:</label>
                <select
                    id="difficulty"
                    value={difficultyLevel}
                    onChange={handleDifficultyChange}>
                    {wordBooks.length > 0 ? (
                        wordBooks.map((wordBook, index) => (
                            <option key={index} value={wordBook}>
                                {wordBook}
                            </option>
                        ))
                    ) : (
                        <option>加载中...</option>
                    )}
                </select>
            </div>

            <div className="word-text">
                <h1>单词检测</h1>
            </div>

            {activeTab === 'learn' ? (
                <div className="learn-section">
                    <div className="word-progress">
                        <h2>当前进度: {currentWordIndex + 1} / {words.length}</h2>
                    </div>

                    <div className="word-card" onClick={handleWordClick}>
                        {words[currentWordIndex]?.word}
                    </div>
                    {showChineseMeaning && (
                        <div className="chinese-meaning">
                            {words[currentWordIndex]?.chineseMeaning}
                        </div>
                    )}
                    <div className="button-group">
                        <button className="remember-button" onClick={handleRememberWord}>
                            记住了✌️
                        </button>
                        <button className="error-button" onClick={handleAddToErrorWords}>
                            加入错词✍️
                        </button>
                        <button className="next-button" onClick={startNewRound}>
                            下一个👉
                        </button>

                    </div>
                </div>
            ) : (
                <div className="review-section">
                    <div className="reviewtext">
                        <h2>
                            复习单词（进度: {reviewWords.length > 0 ? `${currentReviewIndex + 1}/${reviewWords.length}` : '0'}）
                        </h2>
                    </div>

                    {reviewWords.length > 0 && currentReviewIndex < reviewWords.length ? (
                        <>
                            <div className="word-card" onClick={handleWordClick}>
                                {reviewWords[currentReviewIndex].word}
                            </div>
                            {showChineseMeaning && (
                                <div className="chinese-meaning">
                                    {reviewWords[currentReviewIndex].chineseMeaning}
                                </div>
                            )}
                            <button
                                className="remember-button"
                                onClick={handleReviewRememberWord}>
                                记住了✌️
                            </button>
                        </>
                    ) : (
                        <div className="no-review-words-warning">
                            <p>目前没有需要复习的单词😉</p>
                        </div>
                    )}
                </div>
            )}
        </div>
    );
};

export default Word;
